from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from server.pao_python.pao.data import string_to_date
from ...service.common import get_info
from ...service.buss_pub.bill_manage import BillManageService, OperationType, Status, TypeId
from ...service.mongo_bill_service import MongoBillFilter


class TransactionService(MongoService):
    '''交易服务'''

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_server = BillManageService(
            self.db_addr, self.db_port, self.db_name, self.db_user, self.db_pwd, self.inital_password, self.session)

    def add_transaction(self, data):
        '''增加交易'''
        res = 'Fail'
        data_info = get_info({**data}, self.session)
        date = data['transaction_date']
        data_info['transaction_date'] = string_to_date(date)
        bill_id = self.bill_manage_server.add_bill(
            OperationType.add.value, TypeId.transaction.value, data_info, 'PT_Transaction')
        if bill_id:
            res = data_info['id']
        return res

    def get_transaction_list(self, condition, page, count):
        '''获取交易清单'''
        collection_name = 'PT_Transaction'
        keys = ['transaction_code', 'party_a', 'party_b', 'id']
        values = self.get_value(condition, keys)
        # 过滤器配置
        _filter = MongoBillFilter()
        _filter\
            .match((C('bill_status') == 'valid') & (C('transaction_code') == values['transaction_code']) & (C('id') == values['id']))\
            .inner_join_bill('PT_User', 'party_a', 'id', 'a_name')\
            .match(C('a_name.name') == values['party_a'])\
            .inner_join_bill('PT_User', 'party_b', 'id', 'b_name')\
            .match(C('b_name.name') == values['party_b'])\
            .project({
                '_id': 0, 'id': 1,
                'transaction_code': 1,
                'party_a': '$a_name.name',
                'party_b': '$b_name.name',
                'transaction_content': 1,
                'transaction_state': 1,
                'transaction_evaluate_a': '$evaluate_a',
                'transaction_evaluate_b': '$evaluate_b'})

        # 分页查询
        res = self.page_query(_filter, collection_name, page, count)
        return res

    def cancel_transaction_by_id(self, data):
        '''取消交易'''
        res = 'Fail'
        fail_id = ''
        up_data = {'transaction_state': '已取消', 'id': data['id']}
        if data['transaction_state'] == '进行中':
            self.bill_manage_server.add_bill(
                OperationType.update.value, TypeId.transaction.value, up_data, 'PT_Transaction')
        else:
            fail_id = data['transaction_code']
        if fail_id == '':
            res = 'Success'
        return res

    def return_transaction_by_id(self, id):
        '''恢复交易'''
        res = 'Fail'
        fail_id = ''
        _filter = MongoFilter()
        _filter.match((C('id') == id) & (
            C('bill_status') == Status.bill_valid.value))
        data = self.query(_filter, 'PT_Transaction')

        if len(data) > 0:
            transaction_state = data[0]['transaction_state']
            transaction_code = data[0]['transaction_code']

        if transaction_state == '已取消':
            up_data = {'transaction_state': '进行中', 'id': id}
            self.bill_manage_server.add_bill(
                OperationType.update.value, TypeId.transaction.value, up_data, 'PT_Transaction')
        else:
            fail_id = transaction_code
        if fail_id == '':
            res = 'Success'
        print('finally', res)
        return res

    def del_transaction_by_id(self, id_list):
        '''删除交易'''
        res = 'Fail'
        fail_list = []
        for i in id_list:
            _filter = MongoFilter()
            _filter.match((C('id') == i) & (
                C('bill_status') == Status.bill_valid.value))
            data = self.query(_filter, 'PT_Transaction')
            transaction_state = data[0]['transaction_state']
            transaction_code = data[0]['transaction_code']
            if transaction_state in ['已完成', '已取消']:
                self.bill_manage_server.add_bill(
                    OperationType.delete.value, TypeId.transaction.value, {'id': i}, 'PT_Transaction')
            else:
                fail_list.append(transaction_code)
        if len(fail_list) > 0:
            res = ','.join(fail_list)+' 删除失败'
        else:
            res = 'Success'
        return res

    def confirm_transaction_by_id(self, id_list):
        '''确认交易'''
        fail_list = []
        for i in id_list:
            _filter = MongoFilter()
            _filter.match((C('id') == i) & (
                C('bill_status') == Status.bill_valid.value))
            data = self.query(_filter, 'PT_Transaction')
            transaction_state = data[0]['transaction_state']
            transaction_code = data[0]['transaction_code']
            if transaction_state == '进行中':
                up_data = {'transaction_state': '已完成', 'id': i}
                self.bill_manage_server.add_bill(
                    OperationType.update.value, TypeId.transaction.value, up_data, 'PT_Transaction')
            else:
                fail_list.append(transaction_code)
        if len(fail_list) > 0:
            res = ','.join(fail_list)+' 确认失败'
        else:
            res = 'Success'
        return res

    def modify_transaction_content(self, data):
        '''修改交易内容'''
        res = 'Fail'
        bill_id = self.bill_manage_server.add_bill(OperationType.update.value,
                                                   TypeId.transaction.value, data, 'PT_Transaction')
        if bill_id:
            res = 'Success'
        return res

    def add_transaction_comment(self, data):
        '''增加评论'''
        res = 'Fail'
        date = data['comment_date']
        data['comment_date'] = string_to_date(date)
        bill_id = self.bill_manage_server.add_bill(
            OperationType.add.value, 'transaction_comment', data, 'PT_Transaction_Comment')
        if bill_id:
            res = 'Success'
        return res

    def del_transaction_comment(self, ids):
        '''删除评论'''
        res = 'Fail'
        for i in ids:
            bill_id = self.bill_manage_server.add_bill(
                OperationType.delete.value, 'transaction_comment', {'id': i}, 'PT_Transaction_Comment')
        if bill_id:
            res = 'Success'
        return res

    def query_transaction_comment_list(self, condition, page, count):
        '''交易清单评论查询
        '''
        keys = ['user_name']
        values = self.get_value(condition, keys)

        _filter = MongoBillFilter()
        _filter.match(C('bill_status') == 'valid')\
               .inner_join_bill('PT_User', 'party_a', 'id', 'a_name')\
               .inner_join_bill('PT_User', 'party_b', 'id', 'b_name')\
               .match((C('a_name.name').like(values['user_name'])) | (C('b_name.name').like(values['user_name'])))\
               .lookup_bill('PT_Transaction_Comment', 'id', 'transaction_id', 'comment_valid_info')\
               .project({'_id': 0, 'comment_score': self.ao.avg('$comment_valid_info.comment_score'), 'transaction_content': 1, 'party_a': '$a_name.name', 'party_b': '$b_name.name', 'transaction_id': '$transaction_code', 'id': 1})
        print(_filter.filter_objects)
        # 分页查询
        res = self.page_query(_filter, 'PT_Transaction', page, count)
        return res

    def query_comment_details_list(self, condition, page, count):
        '''评论详情查询
        '''
        keys = ['ids']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('transaction_id').inner(values['ids']))\
               .inner_join_bill('PT_User', 'comment_person_id', 'id', 'conmment_person_info')\
               .inner_join_bill('PT_Transaction', 'transaction_id', 'id', 'trans_info')\
               .project({'_id': 0, 'comment_person': '$conmment_person_info.name', 'transaction_id': '$trans_info.transaction_code', 'comment_content': 1, 'comment_score': 1})\
               .sort({'transaction_id': 1})

        # 分页查询
        res = self.page_query(_filter, 'PT_Transaction_Comment', page, count)
        return res
